<template>
  <div class="dashboard-container">
    <div class="welcome-section">
      <div class="welcome-content">
        <h1>欢迎回来，{{ userInfo?.realName || '管理员' }}！</h1>
        <p class="welcome-desc">{{ getCurrentTime() }} | 今天是个好天气，适合处理工作</p>
      </div>
      <div class="welcome-avatar">
        <el-avatar :size="80" :src="userInfo?.avatar || ''">
          {{ userInfo?.realName?.charAt(0) || 'U' }}
        </el-avatar>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon customer">
          <el-icon size="40"><User /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.customerCount }}</div>
          <div class="stat-label">客户总数</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon business">
          <el-icon size="40"><Suitcase /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.businessCount }}</div>
          <div class="stat-label">业务总数</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon order">
          <el-icon size="40"><Tickets /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.orderCount }}</div>
          <div class="stat-label">工单总数</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon revenue">
          <el-icon size="40"><Money /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">¥{{ formatMoney(stats.totalRevenue) }}</div>
          <div class="stat-label">总营收</div>
        </div>
      </div>
    </div>

    <!-- 图表和数据区域 -->
    <div class="charts-grid">
      <!-- 最近客户 -->
      <div class="chart-card">
        <div class="card-header">
          <h3>最近新增客户</h3>
          <el-button type="text" @click="$router.push('/dashboard/customers')">
            查看更多 <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
        <div class="card-content">
          <el-table :data="recentCustomers" style="width: 100%">
            <el-table-column prop="companyName" label="公司名称" />
            <el-table-column prop="contactPerson" label="联系人" />
            <el-table-column prop="customerLevel" label="客户等级">
              <template #default="{ row }">
                <span :class="`level-tag ${row.customerLevel}`">{{ row.customerLevel }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间">
              <template #default="{ row }">
                {{ formatDate(row.createdAt) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 待处理工单 -->
      <div class="chart-card">
        <div class="card-header">
          <h3>待处理工单</h3>
          <el-button type="text" @click="$router.push('/dashboard/work-orders')">
            查看更多 <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
        <div class="card-content">
          <el-table :data="pendingOrders" style="width: 100%">
            <el-table-column prop="title" label="工单标题" />
            <el-table-column prop="customerName" label="客户" />
            <el-table-column prop="priority" label="优先级">
              <template #default="{ row }">
                <span :class="`priority-tag ${getPriorityClass(row.priority)}`">{{ row.priority }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间">
              <template #default="{ row }">
                {{ formatDate(row.createdAt) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions">
      <h3>快速操作</h3>
      <div class="actions-grid">
        <div class="action-item" @click="$router.push('/dashboard/customers')">
          <el-icon size="32"><UserFilled /></el-icon>
          <span>新增客户</span>
        </div>
        <div class="action-item" @click="$router.push('/dashboard/businesses')">
          <el-icon size="32"><Briefcase /></el-icon>
          <span>创建业务</span>
        </div>
        <div class="action-item" @click="$router.push('/dashboard/work-orders')">
          <el-icon size="32"><DocumentAdd /></el-icon>
          <span>创建工单</span>
        </div>
        <div class="action-item" @click="$router.push('/dashboard/employees')">
          <el-icon size="32"><Avatar /></el-icon>
          <span>员工管理</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useUserStore } from '@/stores/user'
import { getDashboardStats, getRecentCustomers, getPendingOrders } from '@/api/dashboard'
import dayjs from 'dayjs'

const userStore = useUserStore()

// 响应式数据
const stats = ref({
  customerCount: 0,
  businessCount: 0,
  orderCount: 0,
  totalRevenue: 0
})

const recentCustomers = ref([])
const pendingOrders = ref([])

// 计算属性
const userInfo = computed(() => userStore.userInfo)

// 获取当前时间
const getCurrentTime = () => {
  const hour = new Date().getHours()
  if (hour < 6) return '凌晨好'
  if (hour < 9) return '早上好'
  if (hour < 12) return '上午好'
  if (hour < 14) return '中午好'
  if (hour < 17) return '下午好'
  if (hour < 19) return '傍晚好'
  return '晚上好'
}

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 格式化金额
const formatMoney = (amount) => {
  return new Intl.NumberFormat('zh-CN').format(amount)
}

// 获取优先级样式类
const getPriorityClass = (priority) => {
  const priorityMap = {
    '低': 'low',
    '中': 'medium', 
    '高': 'high',
    '紧急': 'urgent'
  }
  return priorityMap[priority] || 'medium'
}

// 获取统计数据
const getStats = async () => {
  try {
    const response = await getDashboardStats()
    if (response.code === 200) {
      stats.value = response.data
      console.log('获取统计数据成功:', response.data)
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 使用模拟数据
    stats.value = {
      customerCount: 15,
      businessCount: 20,
      orderCount: 25,
      totalRevenue: 1888000
    }
  }
}

// 获取最近客户
const getRecentCustomersData = async () => {
  try {
    const response = await getRecentCustomers({ 
      page: 1, 
      pageSize: 5
    })
    if (response.code === 200) {
      // 修复：后端返回的数据结构是 { data: [...], total: 10, page: 1, size: 10 }
      let responseData = response.data
      if (responseData && responseData.data && Array.isArray(responseData.data)) {
        recentCustomers.value = responseData.data
        console.log('获取最近客户成功:', responseData.data.length, '条')
      } else if (responseData && Array.isArray(responseData)) {
        recentCustomers.value = responseData
      } else {
        recentCustomers.value = []
      }
    }
  } catch (error) {
    console.error('获取最近客户失败:', error)
    // 使用模拟数据
    recentCustomers.value = [
      {
        companyName: '北京科技有限公司',
        contactPerson: '张总',
        customerLevel: 'A',
        createdAt: '2024-01-15 10:30:00'
      },
      {
        companyName: '上海贸易公司',
        contactPerson: '李经理',
        customerLevel: 'B',
        createdAt: '2024-01-14 14:20:00'
      }
    ]
  }
}

// 获取待处理工单
const getPendingOrdersData = async () => {
  try {
    const response = await getPendingOrders({ 
      page: 1, 
      pageSize: 5
    })
    if (response.code === 200) {
      // 修复：后端返回的数据结构是 { data: [...], total: 10, page: 1, size: 10 }
      let responseData = response.data
      if (responseData && responseData.data && Array.isArray(responseData.data)) {
        pendingOrders.value = responseData.data
        console.log('获取待处理工单成功:', responseData.data.length, '条')
      } else if (responseData && Array.isArray(responseData)) {
        pendingOrders.value = responseData
      } else {
        pendingOrders.value = []
      }
    }
  } catch (error) {
    console.error('获取待处理工单失败:', error)
    // 使用模拟数据
    pendingOrders.value = [
      {
        title: '系统登录异常',
        customerName: '北京科技有限公司',
        priority: '高',
        createdAt: '2024-01-16 09:00:00'
      },
      {
        title: '数据导入问题',
        customerName: '上海贸易公司',
        priority: '中',
        createdAt: '2024-01-16 10:00:00'
      }
    ]
  }
}

// 页面初始化
onMounted(() => {
  getStats()
  getRecentCustomersData()
  getPendingOrdersData()
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
}

.welcome-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  border-radius: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  
  .welcome-content {
    h1 {
      font-size: 28px;
      font-weight: 600;
      margin-bottom: 8px;
    }
    
    .welcome-desc {
      font-size: 16px;
      opacity: 0.9;
    }
  }
  
  .welcome-avatar {
    .el-avatar {
      background: rgba(255, 255, 255, 0.2);
      color: white;
      font-size: 32px;
      font-weight: 600;
    }
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
  
  .stat-card {
    background: white;
    padding: 24px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    
    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      
      &.customer { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
      &.business { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; }
      &.order { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; }
      &.revenue { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); color: white; }
    }
    
    .stat-content {
      .stat-number {
        font-size: 24px;
        font-weight: 600;
        color: #333;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.charts-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
  
  .chart-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    
    .card-header {
      padding: 20px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h3 {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin: 0;
      }
    }
    
    .card-content {
      padding: 20px;
    }
  }
}

.quick-actions {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 20px;
  }
  
  .actions-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 20px;
    
    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;
      border-radius: 8px;
      border: 2px dashed #e0e0e0;
      cursor: pointer;
      transition: all 0.3s ease;
      
      .el-icon {
        color: #666;
        margin-bottom: 8px;
      }
      
      span {
        font-size: 14px;
        color: #666;
      }
      
      &:hover {
        border-color: #409eff;
        background: #f0f9ff;
        
        .el-icon,
        span {
          color: #409eff;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
  
  .welcome-section {
    flex-direction: column;
    text-align: center;
    
    .welcome-avatar {
      margin-top: 20px;
    }
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style> 